package com.share.rmi;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import com.share.Mbean.Hello;

/**
 * MBean接入层: 使用rmi,远程访问
 */
public class HelloRMIAgent {

	public static void main(String[] args)  throws Exception {
		//MBean生成和注册
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		ObjectName helloName = new ObjectName("jmxstudy:name=hello");
		server.registerMBean(new Hello(), helloName);

		//建立MBean接入层
		try {
			// 注册一个端口，绑定url后用于客户端通过rmi方式连接JMXConnectorServer
			LocateRegistry.createRegistry(9999);
			// URL路径的结尾可以随意指定，但如果需要用Jconsole来进行连接，则必须使用jmxrmi
			String urlString  = "service:jmx:rmi://localhost:9999/jndi/rmi://localhost:9999/jmxDefault";
			JMXServiceURL url = new JMXServiceURL(urlString);
			JMXConnectorServer jcs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
			System.out.println("HelloRMIAgent start...");
			jcs.start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
